# coding:utf-8
"""
Class 重构 unzip 。
"""
import sys
sys.path.extend(['C:\\Py', 'C:\\Py\\e_mail'])

from os import system, mkdir, popen, remove, getpid
from os.path import exists
import time, codecs
from e_mail.send.cl_send_mail import SendMail


class Unzip:
    """通过WinRAR.exe进行解压缩。"""
    EXE_UNZIP = "C:\\Program Files\\WinRAR\\WinRAR.exe"
    EXE_NOTEPAD = r"C:\Program Files\Notepad++\notepad++.exe"
    f_ErrorLog = r'D:/SelfLog/unzip_ErrorLog.txt'
    f_fileList = './_sup/fileList.txt'

    def __init__(self, source_dir, target_dir):
        self.SOURCE_DIR = source_dir
        self.TARGET_DIR = target_dir
        self._init_file()

    def _init_file(self):
        print("* initialize ...")
        if not exists('./_sup/'): mkdir('./_sup/')
        if not exists('D:/SelfLog/'): mkdir('D:/SelfLog/')
        if exists(self.f_ErrorLog): remove(self.f_ErrorLog)
        if exists(self.f_fileList): remove(self.f_fileList)

    def get_file_path(self):
        for _dir in self.SOURCE_DIR: system(f'dir /b /a:-D /s  {_dir}  >> {self.f_fileList}')  # D:
        _f = open('./_sup/fileList.txt', 'r', encoding='gbk').read().split('\n')
        remove(self.f_fileList)
        return _f

    def unzip(self):
        for _f in self.get_file_path():
            if _f.endswith('zip'):
                ss = f'"{self.EXE_UNZIP}" x  -o- -ilog{self.f_ErrorLog} -ibck -inul -kb "{_f}"  *.* "{self.TARGET_DIR}\\"'
                # x：解压                     -o-：跳过已存在文件           -ibck：后台   -kb：保留解压时损坏的文件
                #                              -ilogFileName:导出错误日志到文件   -inul：停用错误信息
                # -or：自动重命名文件
                print(ss)
                popen(ss).read()


if __name__ == '__main__':
    source = ['F:\\迅雷下载', 'D:\\迅雷下载', 'F:\\H_zip\\Diszip']
    target = r'F:\\H_temp\\20191105\\'
    dic_sender = {'pop_host': 'pop.qq.com',
                  'smtp_host': 'smtp.qq.com',
                  'user': '1491311784@qq.com',
                  'passwd': 'fxvvlznnwkclheic',
                  }
    a = Unzip(source, target)
    a.unzip()
    try:
        with open(a.f_ErrorLog, 'r', encoding='utf_16')as f:
            SendMail(**dic_sender).send_one_mail('lee_cq@icloud.com', '解压情况', f.read())
    except:
        SendMail(**dic_sender).send_one_mail('lee_cq@icloud.com', '解压情况',
                                             f"[{time.strftime('%Y-%m-%D %H:%M')}]一切正常。"
                                             f"已经将所有文件提取到{a.TARGET_DIR}")
